/**
 *
 */
package com.swim.phonenumprivacy.web;

import com.jeesite.common.config.Global;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.swim.natatoriuminfo.entity.NatatoriumInfo;
import com.swim.natatoriuminfo.service.NatatoriumInfoService;
import com.swim.pay.web.SwimPayController;
import com.swim.phonenumprivacy.entity.NatatoriumCallInfo;
import com.swim.phonenumprivacy.entity.NatatoriumPhonenumBind;
import com.swim.phonenumprivacy.service.BindAxnExtensionService;
import com.swim.phonenumprivacy.service.NatatoriumCallInfoService;
import com.swim.phonenumprivacy.service.NatatoriumPhonenumBindService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 号码隐私保护Controller
 *
 * @author 刘军武
 * @version 2023-12-17
 */
@Controller
@RequestMapping(value = "${adminPath}/phonenumprivacy")
public class PhonenumprivacyController extends BaseController {

    @Autowired
    private BindAxnExtensionService axnExtensionService;

    @Autowired
    private NatatoriumInfoService natatoriumInfoService;

    @Autowired
    private NatatoriumPhonenumBindService natatoriumPhonenumBindService;

    @Autowired
    private NatatoriumCallInfoService natatoriumCallInfoService;

    private Logger logger = LoggerFactory.getLogger(SwimPayController.class);

    /**
     * 号码绑定
     */
    @PostMapping(value = "phonenumBind")
    @ResponseBody
    public String phonenumBind(String NatatoriumInfoId) {
        logger.info("进入号码绑定接口，入参游泳馆id  == " + NatatoriumInfoId);
        //查询游泳馆对应的客服电话
        NatatoriumInfo natatoriumInfo = natatoriumInfoService.get(NatatoriumInfoId);
        String phoneA = natatoriumInfo.getPhone();        // 联系电话
        /*
        //获取当前操作用户的电话
        User user = UserUtils.getUser();
        String phoneB = user.getLoginCode(); //登录账号

        AxnDTO axnDTO = new AxnDTO();
        axnDTO.setPhoneA(phoneA);
        axnDTO.setPhoneB(phoneB);
        LocalDateTime now = LocalDateTime.now(); // 获取当前时间
        LocalDateTime expirationTime = now.plus(Duration.ofMinutes(5)); // 当前时间往后推5分钟
        axnDTO.setExpiration(expirationTime);
        AxnVO axnVO = axnExtensionService.bindAxnExtension(axnDTO);
        logger.error("分机号 = " + axnVO.getExtension());
        logger.error("场馆客服号码 = " + axnVO.getPhoneA());
        logger.error(axnVO.getPhoneB());
        logger.error("隐私号 = " + axnVO.getSecretNo());
        logger.error("绑定关系id = " + axnVO.getSubsId());
        logger.error(axnVO.toString());
        Assert.notNull(axnVO, "绑定成功");

        //保存绑定记录
        NatatoriumPhonenumBind natatoriumPhonenumBind = new NatatoriumPhonenumBind();
        natatoriumPhonenumBind.setNatatoriumInfoId(natatoriumInfo.getId());        // 游泳馆信息id
        natatoriumPhonenumBind.setSubsId(axnVO.getSubsId());        // 绑定关系id
        natatoriumPhonenumBindService.save(natatoriumPhonenumBind);

        StringStorageUtil subsIdStorageUtil = new StringStorageUtil();
        subsIdStorageUtil.storeData(axnVO.getSubsId() + "+" + axnVO.getSecretNo());
         */
        return renderResult(Global.TRUE, text("号码绑定成功！"), phoneA);
    }

    /**
     * 接收呼叫回执数据
     */
    @PostMapping("/receiveData")
    @ResponseBody
    public Map<String, Object> receiveData(@RequestBody List<Map<String, Object>> data) {
        logger.error("进入接收呼叫结束后话单报告数据方法");
        // 处理数据  
        data.forEach(item -> {
            // 遍历每个元素并处理你需要的字段，例如打印所有字段
            item.forEach((key, value) ->
                    logger.error(key + ": " + value)
            );
            //查询绑定记录
            NatatoriumPhonenumBind natatoriumPhonenumBind = new NatatoriumPhonenumBind();
            natatoriumPhonenumBind.setSubsId(item.get("sub_id").toString());        // 绑定关系id
            List<NatatoriumPhonenumBind> natatoriumPhonenumBindList = natatoriumPhonenumBindService.findList(natatoriumPhonenumBind);
            //新增呼叫记录
            NatatoriumCallInfo natatoriumCallInfo = new NatatoriumCallInfo();
            natatoriumCallInfo.setNatatoriumInfoId(natatoriumPhonenumBindList.get(0).getNatatoriumInfoId());        // 游泳馆信息id
            natatoriumCallInfo.setPeerNo(item.get("peer_no").toString());        // 主叫号码
            natatoriumCallInfo.setPhoneNo(item.get("phone_no").toString());        // 被叫号码
            natatoriumCallInfo.setCalledDisplayNo(item.get("called_display_no").toString());        // 显示号码
            natatoriumCallInfo.setCallTime(item.get("call_time").toString());        // 主叫拨打时间
            natatoriumCallInfo.setStartTime(item.get("start_time").toString());        // 被叫接听时间
            natatoriumCallInfo.setReleaseTime(item.get("release_time").toString());        // 通话结束时间
            //计算通话时长
            String callDurationStr = "0秒";
            if (StringUtils.isNoneEmpty(item.get("start_time").toString()) && StringUtils.isNoneEmpty(item.get("release_time").toString())) {
                LocalDateTime start = LocalDateTime.parse(item.get("start_time").toString());
                LocalDateTime end = LocalDateTime.parse(item.get("release_time").toString());
                Duration duration = Duration.between(start, end);
                long minutes = duration.toMinutes();
                long seconds = duration.getSeconds() % 60;  // extract the remaining seconds after division by 60  
                callDurationStr = minutes + " 分钟 " + seconds + " 秒";
            }
            natatoriumCallInfo.setCallDuration(callDurationStr);    // 通话时长
            natatoriumCallInfoService.save(natatoriumCallInfo);
        });
        // 设置响应信息  
        Map<String, Object> response = new HashMap<>();
        response.put("msg", "接收成功");
        response.put("code", 0);
        return response;
    }
}